﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.CodeCoverage;
using System.Diagnostics;
using log4net;
namespace PreCommitHook
{
    class Program
    {
        protected static readonly ILog log = LogManager.GetLogger(typeof(Program));
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
           
            string arg1 = args[0];
            string arg2 = args[1];
            log.Info(String.Format("Argument 1 svnRepositoryPath pre-commit hook execution: {0}", arg1));
            log.Info(String.Format("Argument 2 pre-commit hook execution: {0}", arg2));

            try
            {
                PreCommitValidator commitValidator = new PreCommitValidator();
                PreCommitResult result = commitValidator.ShouldProceedWithCommit(args[0], args[1]);

                if (result.IsValid)
                    AllowCommit();
                else
                    PreventCommit(result.ErrorMessage);
            }

            catch (Exception e)
            {
                PreventCommit(e.Message + e.StackTrace);
            }
           
        }

        private static void PreventCommit(string errorMessage)
        {
            if (String.IsNullOrEmpty(errorMessage) == false)
            {
                Console.Error.WriteLine("------------------------COMMIT POLICY VIOLATION ------------------------");
                Console.Error.WriteLine(errorMessage);
                Console.Error.WriteLine("-------YOUR COMMIT HAS BEEN ROLLED BACK. CONTACT YOUR TEAM LEADER-------");
            }

            Environment.Exit(1);
        }

        /// <summary>
        /// Allows the commit by returning expected exit code for success
        /// </summary>
        private static void AllowCommit()
        {
            Environment.Exit(0);
        }
    }
}
